<?php

/**
 * Description of Translator class
 *
 * @author Pavel A. Savchuk
 */
class RCMS_Object_Parser_Translator {

/**
 * Content for parsing
 *
 * @var string
 */
	private $_content = '';

	private $_configArray = '';

	private $_cache = '';

	private $_noCache = array();

	private $_cacheDisabled = true;

	protected $_model;

	protected $_languageId;

	protected $_sitePath;

	protected $_siteUrl;
	/**
	 * Constructor
	 *
	 * @param boolean $allowModification
	 * @param string $content
	 * @param array $pageData
	 */
	public function  __construct($languageId) {
		$this->_model = new RCMS_Object_Parser_TranslatorModel();
		$this->_configArray = $this->_model->selectAllConfigData();
		$this->_languageId = $languageId;//$this->_model->selectLanguageId($this->_configArray['translate_language']);
		$this->_sitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
		$this->_siteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;

		if(empty ($this->_configArray))
			$this->_configArray=null;
		//setting up caching
		$frontendOptions = array(
			'lifetime' => 7200, // cache lifetime of 2 hours
			'automatic_serialization' => true
		);
		$backendOptions = array(
			'cache_dir' => '../public/tmp/cache/' // Directory where to put the cache files
		);
		$this->_cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
	}

	/**
	 * Main entry point for parser
	 *
	 * @return string
	 */
	public function processScreen($content) {

		$this->setContent($content);
		$this->_parse();
		return $this->getContent();
	}


	/**
	 * Parse method. Replace containers, variables, etc...
	 *
	 */
	private function _parse() {
		$variables = $this->_findLexems();
		if(empty ($variables)) {
			return;
		}
		foreach ($variables as $variable) {
			if($this->_cacheDisabled) {
				$variableCachedContent = '';
			}
			else {
				$variableCachedContent = $this->_loadFromCache($variable);
			}

			if(trim($variable)!=="") {
				$lexemId = $this->getIdOfOriginalValue(trim($variable));
				//if($lexemId == 141)
				$replacement = $this->getTranslatedValue($lexemId);
			}else {
				$replacement = "!Wrong translation input!";
			}

			if(!$this->_cacheDisabled) {
				$this->_saveToCache($replacement, $variable . $this->_pageData['id']);
			}

			$this->_replaceLexems($variable, $replacement,$lexemId);
		}
		$this->_parse();
	}

	/**
	 * Replace system varriables
	 *
	 * @param string $variable
	 * @param string $replace
	 */
	private function _replaceLexems($variable, $replace,$lexemId) {
		
		$link="";
  if ($this->isTranslated($lexemId)) {
                    $link = '<a  title="Edit Lexem \''.$variable.'\'" href="javascript:;" onclick="tb_show(\'\',\'' . $this->_siteUrl . 'sys/backend_translate/edit/lexemId/'.$lexemId.'?TB_iframe=true&height=210&width=445\',\'\')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editt.png" alt="Edit Lexem \''.$variable.'\'"  /></a>';
  } else {
                    $link = '<a title="Translate Lexem \''.$variable.'\'" href="javascript:;" onclick="tb_show(\'\',\'' . $this->_siteUrl . 'sys/backend_translate/translate/lexemId/'.$lexemId.'?TB_iframe=true&height=210&width=445\',\'\')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/translatet.png" alt="Translate Lexem \''.$variable.'\'" /></a>';
  }
  $pattern = '/(<.* value=\")({%' . preg_replace('/([\/\\\]){1}/', '\$1', $variable) . '%})(\".*>)/i';
  $replacement = "\${1}$replace\$3" .$link;
  $this->_content = preg_replace($pattern, $replacement, $this->_content);

  $pattern = '/(<button.*>)({%' . preg_replace('/([\/\\\]){1}/', '\$1', $variable) . '%})(<\/button>)/i';
  $replacement = "\${1}$replace\${3}" . $link;
  $this->_content = preg_replace($pattern, $replacement, $this->_content);

  $pattern = '/(<a.*>)({%' . preg_replace('/([\/\\\]){1}/', '\$1', $variable) . '%})(<\/a>)/i';
  $replacement = "\${1}$replace\$3" . $link;
  $this->_content = preg_replace($pattern, $replacement, $this->_content);



  $this->_content = str_replace('{%' . $variable . '%}', $replace . $link, $this->_content);
	}

	/**
	 * Find containers in content
	 *
	 * @return array
	 */
	private function _findLexems() {
		//preg_match_all('/{\%([\w\d\s\.:\?]+)\%}/', $this->_content, $found);
        preg_match_all('/{%([^%}]+)%}/', $this->_content, $found);
		return $found[1];
	}


	private function _loadFromCache($cacheId) {
		$content = $this->_cache->load($cacheId);
		if(!$content) {
			return false;
		}
		return $content;
	}

	private function _saveToCache($content, $cacheId) {
		if(!in_array($cacheId, $this->_noCache)) {
			$this->_cache->save($content, $cacheId);
		}
	}

	public function setContent($content) {
		$this->_content = trim($content);
	}

	public function getContent() {
		return $this->_content;
	}

	public function getIdOfOriginalValue($originalValue) {
		if($originalValue) {
			$result = $this->_model->selectIdOfOriginalValue($originalValue);
			if(!$result) {
				$result = $this->_model->insertOriginalValue($originalValue);
			}
			return $result;
		}
		return;
	}

	public function getOriginalValue($lexemId) {
		if($lexemId) {
			$result = $this->_model->selectOriginalValue($lexemId);
			return $result;
		}
		return;
	}

	public function getTranslatedValue($lexemId) {
		$link = "";
		$translation = $this->_model->selectTranslatedLexem($lexemId,$this->_languageId);
		if($translation == false) {
			$translation = $this->getOriginalValue($lexemId);
			return $translation['original_value'];
		}else {
			return $translation['value'];
		}
	}

	public function getLanguageId($language) {
		$languageId = $this->_model->selectLanguageId($language);
		return $languageId;
	}

	public function isTranslated($lexemId){
		$translation = $this->_model->selectTranslatedLexem($lexemId,$this->_languageId);
		if($translation)
		return true;
		return false;
	}

}



